package cn.db101.fairy.service

import cn.binarywang.wx.miniapp.api.WxMaService
import cn.db101.fairy.component.Slf4j
import cn.db101.fairy.component.Slf4j.Companion.log
import cn.db101.fairy.entity.User
import cn.db101.fairy.entity.UserCollect
import cn.db101.fairy.mapper.FairyDetailMapper
import cn.db101.fairy.mapper.UserCollectMapper
import com.mybatisflex.core.query.QueryWrapper
import com.mybatisflex.kotlin.extensions.db.insert
import com.mybatisflex.kotlin.extensions.db.queryOne
import com.mybatisflex.kotlin.extensions.db.update
import com.mybatisflex.kotlin.extensions.kproperty.eq
import com.mybatisflex.kotlin.extensions.wrapper.whereWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * @author zooy
 * @since 2024/7/10-16:41
 */
@Service
@Slf4j
class UserService {

    @Autowired
    lateinit var wxMaService: WxMaService

    @Autowired
    lateinit var userCollectMapper: UserCollectMapper

    @Autowired
    lateinit var fairyDetailMapper: FairyDetailMapper

    fun wxLogin(code: String): User? {

        log.info("获取到的code：{}", code)
        val sessionResult = wxMaService.jsCode2SessionInfo(code)


        // 获取openId
        val openid = sessionResult.openid

        log.info("返回的openid：{}", openid)

        // 查询用户是否存在
        val user: User? = queryOne {
            whereWith {
                User::openId eq openid
            }
        }

        if (user == null) {
            // 插入用户
            insert(User().also {
                it.openId = openid
                it.sessionKey = sessionResult.sessionKey
            })

        }

        return user

    }

    fun updateUser(user: User) {

        // 更新用户头像和昵称
        update<User> {
            User::avatarUrl set user.avatarUrl
            whereWith {
                User::openId eq user.openId
            }
        }

    }

    fun toggleCollect(collect: UserCollect) {
        if (queryOne<UserCollect> {
            whereWith {
                (UserCollect::userId eq collect.userId).and(UserCollect::detailId eq collect.detailId)
            }
        } == null) {
            insert(collect)
            // 童话故事的收藏数同样加1
            fairyDetailMapper.addCollects(collect.detailId)
        } else {
            userCollectMapper.deleteByQuery(QueryWrapper.create()
                .eq(UserCollect::userId, collect.userId)
                .eq(UserCollect::detailId,collect.detailId))
            // 童话故事的收藏数同样加1
            fairyDetailMapper.delCollects(collect.detailId)
        }
    }


    fun queryCollect(collect: UserCollect): UserCollect? {

        return queryOne<UserCollect> {
            whereWith {
                (UserCollect::userId eq collect.userId).and(UserCollect::detailId eq collect.detailId)
            }
        }
    }

}
